const db = require('../db/index')
const RunSql = async (sql, val) => {
  return new Promise(resolve => {
    db.query(sql, val, (err, result) => {
      if (err) return err;
      resolve(result)
    })
  })
}

// 获取菜单
exports.getMenu = async (req, res) => {
  const user = req.auth;
  let routers = [];
  //按照用户名获取父级菜单
  const selectSql = 'select * from father_menu where byname=?'
  let fatherList = await RunSql(selectSql, user.username);
  if (fatherList.length) {
    const selectChildSql = 'select * from children_menu'
    let childList = await RunSql(selectChildSql);
    fatherList.map(FItem => {
      let childPathList = [];
      routers.push({
        path: FItem.path,
        name: FItem.name,
        meta: {
          title: FItem.title,
        },
        component: FItem.name,
        children: childPathList
      })
      childList.map(CItem => {
        if (FItem.name == CItem.father_name) {
          CItem.meta = { title: CItem.title };
          childPathList.unshift(CItem);
        }
      })
    })
    setTimeout(() => {
      res.cc('获取成功', 200, routers)
    }, 1000)
  } else {
    res.cc('获取成功', 200, fatherList)
  }
}